package Concurrency2.Inteview01_ThreadPool.version01;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

public class WorkerThread extends Thread {
    private BlockingQueue<Runnable> taskQueue;
    private static AtomicInteger workerId = new AtomicInteger(1);

    public WorkerThread(BlockingQueue<Runnable> taskQueue) {
        this.taskQueue = taskQueue;
        // 创建日志
        System.err.println("---------------------------------Worker Thread Creation times: "+workerId.getAndIncrement()+" ID: "+getId());
    }

    /**
     * 作用: 获取任务队列taskQueue中的任务, 并执行.
     */
    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            try {
                Runnable task = taskQueue.take(); // 阻塞获取任务
                task.run(); // 直接调用Thread的run()方法, 而不是调用start()方法启动一个线程.
            } catch (InterruptedException e) {
                System.out.println("ThreadID: "+getId()+" interrupted!");
                break;
            }
        }
    }
}
